
<template>
    <view @click="open">
        <uv-picker @close="close" ref="picker" :loading="loading" @confirm="confirm" @change="change" />
        <uv-input placeholder="请选择所在区域" readonly :suffixIcon="show ? 'arrow-up' : 'arrow-down'"
            :value="modelValue.join(',')" />
    </view>
</template>

<script lang="ts">

import { TaDataBase } from "@/utils";
import { defineComponent } from "vue";

function deepCopy(values: any[]) {
    return JSON.parse(JSON.stringify(values));
}

export default defineComponent({
    props: {
        cols: {
            type: Number,
            default: 3
        },
        modelValue: {
            type: Array,
            default: []
        }
    },
    emits: ['confirm', 'update:modelValue'],
    data() {
        return {
            show: <boolean>false,
            values: <any[]>[],
            columns: <any[]>[],
            regions: <any[]>[],
            loading: <boolean>true,
        }
    },
    mounted() {
        this.loadData()
        this.values = deepCopy(this.modelValue || []);
        for (let i = 0; i < this.cols; i++) this.columns.push([]);
    },
    methods: {
        loadData() {
            TaDataBase.region().then((data: any) => {
                this.regions = data;
                this.loading = false;
                this.applyData();
            })
        },
        open() {
            // @ts-ignore
            this.$refs.picker.open()
            this.show = true;
            console.log(this.show)
        },
        close() {
            this.show = false;
            console.log(this.show)
        },
        change(e: any) {
            const { columnIndex, index } = e
            this.values[columnIndex] = this.columns[columnIndex][index];
            this.applyData()
        },
        confirm() {
            this.$emit('update:modelValue', deepCopy(this.values))
        },
        applyData() {
            let items: any[] = this.regions;
            let index: any[] = new Array(this.cols).fill(0);
            for (let i = 0; i < this.cols; i++) {
                let tmps: any[] = [];
                let curr: string = this.values[i] || '';
                items.map((xx: any, ii) => {
                    tmps.push(xx.value)
                    curr === xx.value && (index[i] = ii);
                })
                this.values[i] = tmps[index[i]];
                this.columns[i] = tmps;
                // @ts-ignore
                this.$refs.picker.setColumnValues(i, tmps)
                items = items[index[i]]['children'] || []
            }
            // @ts-ignore
            this.$refs.picker.setIndexs(index, true)
        }
    }
})
</script>

<style lang="scss" scoped></style>